package com.dynamic.data.source.config.datasource;

import com.dynamic.data.source.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.*;
import org.springframework.lang.Nullable;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.sql.DataSource;

/**
 * 开发公司：联信
 * 版权：联信
 * <p>
 * Annotation
 *
 * @author 刘志强
 * @created Create Time: 2021/1/26
 */
public class CustomDataSourceTransactionManager extends DataSourceTransactionManager {

    @Autowired
    private HttpServletRequest httpServletRequest;

    @Nullable
    private DataSource dataSource;
    private boolean enforceReadOnly;

    public CustomDataSourceTransactionManager() {
        this.enforceReadOnly = false;
        this.setNestedTransactionAllowed(true);
    }

    public CustomDataSourceTransactionManager(DataSource dataSource) {
        this();
        this.setDataSource(dataSource);
        this.afterPropertiesSet();
    }

    @Override
    public void setDataSource(@Nullable DataSource dataSource) {
        if (dataSource instanceof TransactionAwareDataSourceProxy) {
            this.dataSource = ((TransactionAwareDataSourceProxy)dataSource).getTargetDataSource();
        } else {
            this.dataSource = dataSource;
        }

    }

    @Override
    @Nullable
    public DataSource getDataSource() {
        try {
            String token = httpServletRequest.getHeader("Authorization");
            if (!StringUtils.isEmpty(token)) {
                User user = DataSourceAdmin.userMap.get(token);
                return DataSourceAdmin.dataSourceMap.get(user.getId()).getDataSource();
            }
        } catch (Exception e) {

        }
        return this.dataSource;
    }

}
